import WxRequest from "./request"
import {
  claerStorage,
  getStorage
} from "./storage"
import {
  toast,
  modal
} from "./extendApi"
import {
  env
} from "./env"
//对WxRequest进行实例化
const instance = new WxRequest({
  baseURL: env.baseUrl,
  timeout: 15000,
  isLoading: false
})

//配置请求拦截器
instance.interceptors.request = (config) => {

  const token = getStorage("token")
  if (token) {
    config.header["token"] = token
  }

  return config
}

//配置响应拦截器
instance.interceptors.response = async (response) => {

  const {
    isSuccess,
    data
  } = response
  //如果isSuccess为false,说明执行了fail回调函数
  if (!isSuccess) {
    wx.toast({
      title: '网络异常，请重试',
      icon: "error"
    })
    return response
  }
  //判断服务器响应的业务状态码
  switch (data.code) {
    case 200:
      return data
    case 208:
      const res = await wx.modal({
        content: "鉴权失败,请重新登录",
        showCancel: false
      })
      if (res) {
        claerStorage()
        wx.navigateTo({
          url: '/pages/login/login',
        })
      }
      return Promise.reject(response)
    default:
      wx.toast({
        title: "程序出现异常，请联系客服或稍后重试",
      })
      return Promise.reject(response)

  }

}

export default instance